#include "app_data.h"


static dev_value_t dev_value = {
    .tuya_net           = TUYA_NET_NONE,
    .record_duration    = 0x00,
};

dev_value_t *dev_obj = &dev_value;

void app_data_read_from_flash(void)
{
    unsigned char buff[USER_FLASH_DATA_SIZE] = {0x00};

    // read from flash
    drv_flash_read(USER_FLASH_DATA_ADDR, buff, USER_FLASH_DATA_SIZE);

    unsigned int _len = (USER_FLASH_DATA_SIZE - USER_FALSH_DATA_OFFSET) / 4;
    unsigned int crc = app_sys_crc32_cal((unsigned int *)&buff[USER_FALSH_DATA_OFFSET], _len);
    unsigned int rcrc = (buff[0] << 24) | (buff[1] << 16) | (buff[2] << 8) | (buff[3]);
    if (crc == rcrc) {
        dev_obj->record_duration = buff[USER_FALSH_DATA_OFFSET];
    }
}

void app_data_write_to_flash(void)
{
    unsigned char buff[USER_FLASH_DATA_SIZE] = {0x00};

    buff[USER_FALSH_DATA_OFFSET]        = dev_obj->record_duration;
    
    unsigned int _len = (USER_FLASH_DATA_SIZE - USER_FALSH_DATA_OFFSET) / 4;
    unsigned int crc = app_sys_crc32_cal((unsigned int *)&buff[USER_FALSH_DATA_OFFSET], _len);
    buff[0] = (crc >> 24) & 0xFF;
    buff[1] = (crc >> 16) & 0xFF;
    buff[2] = (crc >> 8) & 0xFF;
    buff[3] = (crc >> 0) & 0xFF;

    // write to flash
    drv_flash_write(USER_FLASH_DATA_ADDR, buff, USER_FLASH_DATA_SIZE);
}